package com.illtamer.infinite.morii.controller;

import com.illtamer.infinite.morii.pojo.MoriiURI;
import com.illtamer.infinite.morii.service.TransportService;
import com.illtamer.infinite.morii.service.IndexService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@Slf4j
@Controller
public class PublicController {

    @Resource(name = "indexService")
    private IndexService indexService;

    @Resource(name = "transportService")
    private TransportService transportService;

    /**
     * https://repo.maven.apache.org/maven2/
     * */
    @RequestMapping("/public/**")
    public void doGetPublicURI(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String uri = request.getRequestURI();
        if ("/public".equals(uri)) {
            response.sendRedirect("/public/");
            return;
        }
        uri = uri.substring(8);
        request.setAttribute("uri", uri);
        if (uri.length() == 0 || uri.endsWith("/")) {
            request.getRequestDispatcher("/doPublic-folder").forward(request, response);
        } else {
            request.getRequestDispatcher("/doPublic-file").forward(request, response);
        }
    }

    @RequestMapping("/doPublic-folder")
    public String doPublicFolder(HttpServletRequest request, Model model) {
        final String uri = (String) request.getAttribute("uri");
        List<MoriiURI> uriList = indexService.getMoriiURIList(uri);
        model.addAttribute("uri", uri)
                .addAttribute("uriList", uriList);
        return "public";
    }

    @RequestMapping("/doPublic-file")
    public void doPublicFile(HttpServletRequest request, HttpServletResponse response) {
        final String uri = (String) request.getAttribute("uri");
        if (uri.length() != 0 && !uri.endsWith("/")) {
            if (!transportService.download(uri, request, response)) {
                response.setStatus(404);
            }
        }
    }

}
